<template>
  <WidgetContainer>
    <div v-loading="isVisualVappShowLoadingProgress && isLoading" class="chartMain" :class="componentStyleClass">
      <div :id="'chartMain' + chartId" class="chartMain-inner" style="width:100%;height: 100%;">
        <Tooltip ref="Tooltip" :component-style="config.config.property.componentStyle" type="echart" />
        <AdvancedLinkageToolbar :wid="widgetInstanceId" :config="config" />
        <ComponentTitle :property="config.config.property" :title-text-style="getCssStyle('title')" />
        <chart
          ref="dataChart"
          v-visual-tooltip="getTooltip()"
          :style="boxBgColor"
          :w="w"
          :h="h"
          :is-show="isShow"
          :is-loading="isLoading"
          :is-no-data="isNoData"
          :config="config"
          :org-config="orgConfig"
          :widget-instance-id="chartId"
          :isDataAbnormal="isDataAbnormal"
          @chart-click="chartClickEvent"
          @chart-mouse="chartMouse"
        ></chart>
        <NoData
          :isNoData="isNoData"
          :boxBgColor="boxBgColor"
          :noDataPromptType="config.config.property.noDataPromptType"
          :noDataPrompt="config.config.property.noDataPrompt"
        />
        <AbnormalData :isDataAbnormal="isDataAbnormal" :boxBgColor="boxBgColor" :abnormalType="abnormalType" />
      </div>
    </div>
  </WidgetContainer>
</template>
<script>
import AdvancedLinkageToolbar from '@/components/common/advanced-linkage/advanced-linkage-toolbar.vue';
import dfCssStyle from '@/components/common/echart/cssStyle-default';
import WidgetContainer from '@/components/common/widget-container/widget-container.vue';
import chartBase from '@/mixin/chart-base.js';
import emitComponentBase from '@/mixin/emit-component-base.js';
import dataModel from '@/models/panel-config-data.js';
import { checkNegative } from '@/utils/util';
import { mapState } from 'vuex';
import AbnormalData from '../common/abnormal-data/abnormal-data.vue';
import ComponentTitle from '../common/component-title/component-title.vue';
import NoData from '../common/no-data/no-data.vue';
import Tooltip from '../common/tooltip/tooltip.vue';
import Chart from './chart';
import { convertData } from './chart-option';
import config from './config/config';

export default {
  name: 'BasicPie',
  components: {
    Chart,
    ComponentTitle,
    NoData,
    Tooltip,
    AdvancedLinkageToolbar,
    WidgetContainer,
    AbnormalData,
  },
  mixins: [chartBase, emitComponentBase],
  props: ['pareentId', 'widgetId', 'widgetInstanceId', 'widgetName', 'identifier', 'layout', 'w', 'h'],
  data() {
    return {
      isLoading: false,
      isNoData: false,
      orgConfig: [],
      isShow: true,
      chartId: '',
      config: null,
      apiResult: [],
      dfCssStyle,
    };
  },
  computed: {
    ...mapState({}),
  },
  watch: {},
  created() {
    this.orgConfig = config;
    this.config = JSON.parse(JSON.stringify(this.orgConfig));
    this.chartId = `${this.widgetInstanceId}_01`;
  },
  mounted() {
    if (window.isLocalEnv) {
      this.loadWidget();
    }
  },
  methods: {

    // 初始加载时 以及 编排面更改配置时 触发
    loadWidget(pageStatus) {
      this.pageStatus = pageStatus;
      this.updateConfigProperty();
      this.updateConfigData();
      if (window.isLocalEnv || this.emitComponentStatus) {
        this.updateParams(pageStatus);
        if (!this.isRealTime) {
          this.debounceGetData();
        }
      }
      this.afterLoadWidget();
      this.checkNegative(this.apiResult);
    },

    // 接收xvue发来的实时数据
    handleRealTimeCommunication(realTimeData) {
      if (this.config.config.property.isDebounce && this.isStopRealData) {
        return;
      }

      const result = this.getResult(realTimeData);
      if (this.isNoData || this.autoRefreshIsSameRes(result)) {
        this.isLoading = false;
        return;
      }
      const { data, property } = this.config.config;

      // api请求，拿到数据
      if (data.dataSourceType !== 'xMinerRedisRealTime') {
        this.getCorrectParams(this.params, data.dataSourceType); // 参数存入xvue，导出数据时使用
      }
      this.apiResult = result;
      this.lastParams = null;
      this.sendDataToConfig(result);
      const convertedData = convertData(result, property);
      if (convertedData === -1) {
        this.$message.error(this.$demoi18n('view.dataSourceTypeErr'));
        this.setDataException();
        return;
      }
      this.generateChart(convertedData);
      this.isLoading = false;
    },

    // api请求获取图表数据  --图表之间的convertData一般都不相同
    getChartData() {
      const { data, property } = this.config.config;

      // 如果dataSourceType为静态数据,把数据放到Vuex，发出事件，然后退出
      if (data.dataSourceType === 'staticData') {
        const result = this.getStaticData();
        this.apiResult = result;
        this.sendDataToConfig(result);
        const convertedData = convertData(result, property);
        this.generateChart(convertedData);

        // 重置数据异常状态
        this.resetAbnormalType();
        return;
      }

      // api请求，拿到数据
      if (data.dataSourceType) {
        this.isNoData = false;
        this.isLoading = true;
        this.autoRefresh();
        const method = `getChartData${data.dataSourceType}`;
        const params = this.getCorrectParams(this.params, data.dataSourceType);
        dataModel[method](params, data)
          .then(result => {
            this.isNoData = !result.length;

            // 重置数据异常状态
            this.resetAbnormalType();
            this.reportIfFieldsError(this.getParams()?.propertyMapping, result);
            if (this.autoRefreshIsSameRes(result)) {
              return;
            }
            this.apiResult = result;
            this.lastParams = null;
            this.sendDataToConfig(result);

            const convertedData = convertData(result, property);
            if (convertedData === -1) {
              this.$message.error(this.$demoi18n('view.dataSourceTypeErr'));
              this.setDataException();
              return;
            }
            this.generateChart(convertedData);
          })
          .catch(err => {
            this.handleChartDataError(err);
          })
          .finally(() => {
            this.isLoading = false;
          });
      } else {
        // 如果在用户面，则给提示
        if (this.$route.name === 'userHomePage') {
          this.$message({
            message: this.$demoi18n('view.dataSourceTypeEmpty'),
            type: 'warning',
          });
        }
      }
    },
    getTooltip() {
      return {
        config: this.config.config.property.tooltip || {},
        vars: {},
        params: this.params,
        parentComp: this,
      };
    },
    checkNegative,
    chartClickEvent(params, data) {
      this.chartClick(params, data);
      if (params.data) {
        this.sendAdvancedLinkagge({
          ...params.data,
          s: params.data.trueName,
          y: params.data.trueValue,
          label: params.data.yLabel,
        });
      }
    },
    handleAsTooltip(filterRes) {
      const { property } = this.config.config;
      const convertedData = convertData(filterRes, property);
      this.generateChart(convertedData);
    },
  },
};
</script>
<style lang="less" scoped>
// 图表通用样式，主要有黑色loading 和 黑色 ‘没有数据’，样式名需一致
@import '../../common/chart.less';
</style>
<style>
/* 全局loading样式修改 */

.chartMain .loading .el-loading-spinner .circular {
  width: 34px !important;
  height: 34px !important;
}

.chartMain .el-dialog__header {
  padding: 9px 20px 10px !important;
  background: #2a3352 !important;
  text-align: left;
  box-sizing: border-box;
  height: 50px;
  line-height: 32px;
}

.chartMain .el-dialog__title {
  text-align: left;
  font-size: 18px;
  line-height: 18px !important;
  color: #b2d3fe !important;
}

.chartMain .el-dialog__body {
  padding: 10px 20px 30px 20px;
  background: #1a2032 !important;
  line-height: 24px;
  font-size: 14px;
}

.chartMain .el-dialog__headerbtn .el-dialog__close {
  color: #b2d3fe !important;
}

.chartMain .dialog-footer {
  text-align: right;
  margin-bottom: -14px;
  margin-right: 4px;
}

.chartMain .el-dialog__headerbtn {
  top: 15px;
  font-size: 18px;
}
</style>
